<template>
  <div class="vehicle-management">
    <h1>车辆管理</h1>
    
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="search-area">
            <el-input
              v-model="searchQuery"
              placeholder="搜索车辆（品牌/型号/状态）"
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div>
            <el-button type="primary" @click="handleAddVehicle">
              <el-icon><plus /></el-icon> 添加车辆
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="filteredVehicles"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="车辆图片" width="100">          
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl || 'https://via.placeholder.com/80x60'"
              :preview-src-list="scope.row.imageUrl ? [scope.row.imageUrl] : []"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 4px;"
              @error="() => {$event.target.src = 'https://via.placeholder.com/80x60'}"
            />
          </template>        
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="model" label="型号" width="100" />
        <el-table-column prop="licensePlate" label="车牌号" width="100" />
        <el-table-column prop="dailyPrice" label="日租金" width="100">
          <template #default="scope">
            ¥{{ scope.row.dailyPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="currentLocation" label="当前位置" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shopId" label="所属车行" width="100" />
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="scope">
            <div style="display: flex; gap: 2px;">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                size="small"
                @click="handleStatusChange(scope.row)"
              >
                {{ scope.row.status === 1 ? '设为维护' : '设为可租' }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
                删除
              </el-button>
            </div>
          </template>

        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑车辆对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑车辆信息' : '添加新车辆'"
      width="600px"
    >
      <el-form :model="vehicleForm" label-width="100px" :rules="rules" ref="vehicleFormRef">
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="vehicleForm.brand" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="vehicleForm.model" />
        </el-form-item>
              <el-form-item label="车牌号" prop="licensePlate">          
                <el-input v-model="vehicleForm.licensePlate" />        
              </el-form-item>        
              <el-form-item label="颜色" prop="color">          
                <el-input v-model="vehicleForm.color" />        
              </el-form-item>        
              <el-form-item label="座位数" prop="seatCount">          
                <el-input-number v-model="vehicleForm.seatCount" :min="1" :max="20" />        
              </el-form-item>        
              <el-form-item label="日租金" prop="dailyPrice">          
                <el-input-number v-model="vehicleForm.dailyPrice" :min="1" :precision="2" :step="10" />        
              </el-form-item>
        <el-form-item label="当前位置" prop="currentLocation">
          <el-input v-model="vehicleForm.currentLocation" />
        </el-form-item>
        <el-form-item label="所属车行" prop="shopId">
          <el-input-number v-model="vehicleForm.shopId" :min="1" />
        </el-form-item>
        <el-form-item label="车辆状态" prop="status">
          <el-select v-model="vehicleForm.status">
            <el-option :value="1" label="可租用" />
            <el-option :value="2" label="已租出" />
            <el-option :value="3" label="维护中" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆图片" prop="imageUrl">
          <el-upload
              class="vehicle-image-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :on-change="handleFileChange"
              ref="uploadRef"
          >
            <img v-if="vehicleForm.imageUrl" :src="vehicleForm.imageUrl" class="preview-image" />
            <div v-if="vehicleForm.imageUrl" class="preview-actions">
              <el-icon @click.stop="handleRemoveFile"><Delete /></el-icon>
            </div>
            <template v-if="!vehicleForm.imageUrl">
              <el-icon v-if="!isUploading" class="upload-icon"><Plus /></el-icon>
              <el-icon v-else class="upload-icon"><Loading /></el-icon>
              <div class="upload-tip">{{ isUploading ? '上传中...' : '点击上传车辆图片' }}</div>
            </template>
          </el-upload>
        <div v-if="vehicleForm.imageUrl" style="margin-top: 5px; display: flex; align-items: center;">
          <span style="font-size: 12px; color: #909399;">图片已上传</span>
          <el-button type="danger" size="small" @click="handleRemoveFile" style="margin-left: 10px;">清除</el-button>
        </div>
      </el-form-item>
        <el-form-item label="车辆描述" prop="description">
          <el-input type="textarea" v-model="vehicleForm.description" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              :loading="isUploading"
              @click="submitVehicleForm"
          >
        {{ isUploading ? '上传中...' : '确认' }}
      </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="300px"
    >
      <div class="delete-confirm">
        确定要删除该车辆吗？此操作不可恢复！
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
    
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { addVehicle } from '@/api/vehicle'
import { nextTick } from 'vue'
import { Loading } from '@element-plus/icons-vue'

export default {
  name: 'VehicleManagement',
  components: {
    Search,
    Plus,
    Loading,
    Delete
  },
  setup() {
    const loading = ref(false)
    const vehicles = ref([])
    const searchQuery = ref('')
    const dialogVisible = ref(false)
    const deleteDialogVisible = ref(false)
    const isEdit = ref(false)
    const vehicleFormRef = ref(null)
    const deleteVehicleId = ref(null)
    const uploadingFile = ref(null)
    const isUploading = ref(false)
    
    // 文件上传请求头    
    const uploadHeaders = ref({      
      Authorization: `Bearer ${localStorage.getItem('token') || ''}`    
    })
    
        // 表单数据    
    const vehicleForm = ref({      
      brand: '',      
      model: '',      
      licensePlate: '',      
      color: '',      
      seatCount: 5,      
      dailyPrice: 100,      
      currentLocation: '',      
      shopId: 1,      
      status: 1,      
      imageUrl: '',      
      description: ''    
    })
    
        // 表单验证规则    
    const rules = {      
      brand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],      
      model: [{ required: true, message: '请输入型号', trigger: 'blur' }],      
      licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],      
      color: [{ required: true, message: '请输入颜色', trigger: 'blur' }],      
      seatCount: [{ required: true, message: '请输入座位数', trigger: 'blur' }],      
      dailyPrice: [{ required: true, message: '请输入日租金', trigger: 'blur' }],      
      currentLocation: [{ required: true, message: '请输入当前位置', trigger: 'blur' }],      
      shopId: [{ required: true, message: '请选择所属车行', trigger: 'blur' }],      
      status: [{ required: true, message: '请选择车辆状态', trigger: 'blur' }]    
    }
    
    const filteredVehicles = computed(() => {
      if (!searchQuery.value) {
        return vehicles.value
      }
      const query = searchQuery.value.toLowerCase()
      return vehicles.value.filter(vehicle => 
        vehicle.brand.toLowerCase().includes(query) ||
        vehicle.model.toLowerCase().includes(query) ||
        getStatusText(vehicle.status).includes(query)
      )
    })
    
    const fetchVehicles = async () => {
      loading.value = true
      try {
        const res = await axios.get('/api/admin/vehicles')
        if (res.data.success) {
          vehicles.value = res.data.data || []
        } else {
          throw new Error(res.data.message || '获取车辆列表失败')
        }
      } catch (error) {
        console.error('获取车辆列表失败:', error)
        ElMessage.error(error.message || '获取车辆列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case 1: return 'success'  // 可租用
        case 2: return 'warning'  // 已租出
        case 3: return 'info'     // 维护中
        default: return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 1: return '可租用'
        case 2: return '已租出'
        case 3: return '维护中'
        default: return '未知'
      }
    }
    
    const handleSearch = () => {
      // 搜索功能通过computed属性filteredVehicles自动实现
    }
    
    const handleAddVehicle = () => {     
      isEdit.value = false      
      vehicleForm.value = {        
        brand: '',        
        model: '',        
        licensePlate: '',        
        color: '',        
        seatCount: 5,        
        dailyPrice: 100,        
        currentLocation: '',        
        shopId: 1,        
        status: 1,        
        imageUrl: '',        
        description: ''      
      }
      // 新增重置验证
      nextTick(() => {
        if (vehicleFormRef.value) {
          vehicleFormRef.value.resetFields()
        }
      })
      dialogVisible.value = true    }
    
    const handleEdit = (row) => {
      isEdit.value = true
      vehicleForm.value = { ...row }
      dialogVisible.value = true
    }

    const submitVehicleForm = async () => {
      // 先验证表单
      if (!vehicleFormRef.value) return
      const valid = await vehicleFormRef.value.validate()
      if (!valid) return

      isUploading.value = true

      try {
        // 1. 先上传图片（如果有）
        let imageUrl = '';
        if (uploadingFile.value) {
          const formData = new FormData();
          formData.append('file', uploadingFile.value);

          // 先上传图片
          const uploadRes = await axios.post(
              '/api/admin/upload/vehicleImage',
              formData,
              {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
                }
              }
          );

          if (!uploadRes.data.success) {
            throw new Error(uploadRes.data.message || '图片上传失败');
          }
          imageUrl = uploadRes.data.data.url;
        }

        // 2. 提交车辆数据（包含图片URL）
        const vehicleData = {
          ...vehicleForm.value,
          imageUrl: imageUrl || vehicleForm.value.imageUrl,
          status: vehicleForm.value.status || 1
        };

        const vehicleRes = await axios.post('/api/vehicle/add', vehicleData);

        if (!vehicleRes.data.success) {
          throw new Error(vehicleRes.data.message || '添加车辆失败');
        }

        ElMessage.success('添加成功');
        dialogVisible.value = false;
        await fetchVehicles();
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.message || '操作失败')
      } finally {
        isUploading.value = false
        uploadingFile.value = null
      }
    };
    
    const handleStatusChange = async (row) => {
      // 切换车辆状态：如果是可租状态，切换为维护状态；如果不是可租状态，切换为可租状态
      const newStatus = row.status === 1 ? 3 : 1
      try {
        const res = await axios.put(`/api/admin/vehicles/${row.id}`, {
          ...row,
          status: newStatus,
          lastMaintenanceTime: newStatus === 3 ? new Date().toISOString() : null
        });
        if (res.data.success) {
          ElMessage.success(`车辆状态已更新为${getStatusText(newStatus)}`)
          fetchVehicles()
        } else {
          ElMessage.error(res.data.message || '操作失败')
        }
      } catch (error) {
        console.error('更改车辆状态失败:', error)
        ElMessage.error('更改车辆状态失败')
      }
    }
    
    const handleDelete = (id) => {      
      deleteVehicleId.value = id      
      deleteDialogVisible.value = true    
    }       
    // 图片上传前的验证
    const beforeImageUpload = (file) => {
      const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
      const isImage = validTypes.includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        ElMessage.error('仅支持 JPG/PNG/WEBP 格式!');
        return false;
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB!');
        return false;
      }

      // 存储文件对象用于后续上传
      uploadingFile.value = file;
      return false; // 关闭自动上传
    };

    const handleUploadRequest = async (options) => {
      try {
        const formData = new FormData();
        formData.append('file', options.file);
        if (vehicleForm.value.id) {
          formData.append('vehicleId', vehicleForm.value.id);
        }

        const res = await axios.post(options.action, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': uploadHeaders.Authorization
          }
        });

        if (res.data.code === 200) {
          options.onSuccess(res.data); // 手动触发成功回调
        } else {
          options.onError(new Error(res.data.message));
        }
      } catch (error) {
        options.onError(error);
      }
    };
    const uploadRef = ref(null)

    // 清理上传状态
    const handleRemoveFile = () => {
      // 如果存在临时URL，需要释放它
      if (vehicleForm.value.imageUrl && vehicleForm.value.imageUrl.startsWith('blob:')) {
        URL.revokeObjectURL(vehicleForm.value.imageUrl)
      }
      vehicleForm.value.imageUrl = '';
      uploadingFile.value = null;
      // 清空上传组件内部文件列表
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    };

        // 图片上传成功的回调 - 实际项目中使用这个，现在我们用base64简化          
    const handleImageUploadSuccess = (res) => {
      if (res.code === 200 && res.data) {
        vehicleForm.value.imageUrl = res.data.url;
        ElMessage.success('图片上传成功');
      } else {
        ElMessage.error(res.message || '图片上传失败');
      }
      isUploading.value = false; // 确保上传状态重置
    };

    const handleFileChange = (file) => {
      if (!file || !file.raw) {
        ElMessage.error('文件选择失败')
        return
      }

      // 存储文件对象用于后续提交时上传
      uploadingFile.value = file.raw
      
      // 仅创建临时URL用于预览，不使用Base64（会导致数据库字段超长）
      const tempUrl = URL.createObjectURL(file.raw)
      vehicleForm.value.imageUrl = tempUrl
    }

    const handleUploadError = (error) => {
      ElMessage.error(`图片上传失败: ${error.message}`);
      isUploading.value = false;
    };
    
    const confirmDelete = async () => {
      if (!deleteVehicleId.value) return
      
      try {
        const res = await axios.delete(`/api/admin/vehicles/${deleteVehicleId.value}`)
        if (res.data.success) {
          ElMessage.success('车辆已删除')
          fetchVehicles()
          deleteDialogVisible.value = false
        } else {
          ElMessage.error(res.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除车辆失败:', error)
        ElMessage.error('删除车辆失败')
      }
    }
    
    onMounted(() => {
      fetchVehicles()
      // 确保鉴权头信息是最新的
      uploadHeaders.value = {
        Authorization: `Bearer ${localStorage.getItem('token') || ''}`
      }
    })
    
    return {
      loading,
      vehicles,
      filteredVehicles,
      searchQuery,
      dialogVisible,
      deleteDialogVisible,
      isEdit,
      vehicleForm,
      vehicleFormRef,
      rules,
      handleSearch,
      handleAddVehicle,
      handleEdit,
      handleStatusChange,
      handleDelete,
      submitVehicleForm,
      confirmDelete,
      getStatusType,
      getStatusText,
      beforeImageUpload,      
      handleImageUploadSuccess,
      uploadHeaders,
      handleFileChange,
      handleUploadRequest,
      uploadRef,
      isUploading,
      handleRemoveFile
    }
  }
}
</script>

<style scoped>
.vehicle-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.delete-confirm {
  text-align: center;
  margin: 20px 0;
}

.vehicle-image-uploader {  
  display: flex;  
  justify-content: 
  center;  
  align-items: center;  
  flex-direction: column;  
  border: 1px dashed #d9d9d9;  
  border-radius: 6px;  
  cursor: pointer;  
  position: relative;  
  overflow: hidden;  
  width: 200px; 
  height: 150px;
  }
  
  .vehicle-image-uploader:hover {  
    border-color: #409eff;
  }
    
    .preview-image {  
      width: 100%;  
      height: 100%;  
      object-fit: cover;
    }
      
    .upload-icon {
      font-size: 28px;
      color: #8c939d;
      width: 28px;
      height: 28px;
    }
        
    .upload-tip {
      margin-top: 10px;
      color: #909399;
      font-size: 12px;
    }
    .preview-actions {
      position: absolute;
      top: 5px;
      right: 5px;
      cursor: pointer;
      background: rgba(0,0,0,0.5);
      padding: 3px;
      border-radius: 50%;
    }
</style> 